﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class TcpServer
{
    private TcpListener _server;
    private const int Port = 5000;

    public void Start()
    {
        try
        {
            // 获取本机IPv4地址（非loopback）
            Console.WriteLine("请输入IPv4地址：");
            var localIP = Console.ReadLine();

            // 创建 TcpListener（封装了 Socket 功能）
            _server = new TcpListener(IPAddress.Parse(localIP), Port);
            // 绑定并开始监听
            _server.Start();

            Console.WriteLine($"Server started on {localIP}:{Port}");

            // 异步监听客户端连接
            _server.BeginAcceptTcpClient(OnClientConnect, _server);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }



    private void OnClientConnect(IAsyncResult ar)
    {
        try
        {
            var listener = (TcpListener)ar.AsyncState;
            var client = listener.EndAcceptTcpClient(ar);

            // 处理客户端数据（读取和发送）
            var handler = new ClientHandler(client);

            // 启动异步接收
            handler.StartReceiving();

            // 继续监听新连接
            _server.BeginAcceptTcpClient(OnClientConnect, _server);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Client error: {ex.Message}");
        }
    }

    private string GetLocalIPv4Address()
    {
        var host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork && !ip.IsIPv6LinkLocal && ip.ToString().StartsWith("10.0"))
            {
                return ip.ToString();
            }
        }
        throw new Exception("No valid IPv4 address found.");
    }
}

// 客户端处理类
public class ClientHandler
{
    private TcpClient _client;
    private NetworkStream _stream;
    private const int BufferSize = 4096;

    public ClientHandler(TcpClient client)
    {
        _client = client;
        _stream = client.GetStream();
    }

    public void StartReceiving()
    {
        try
        {
            var buffer = new byte[BufferSize];
            _stream.BeginRead(buffer, 0, buffer.Length, OnReceiveData, buffer);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Receive error: {ex.Message}");
            _client.Close();
        }
    }


    // 处理客户端数据（读取和发送）
    private void OnReceiveData(IAsyncResult ar)
    {
        try
        {
            var buffer = (byte[])ar.AsyncState;
            int bytesRead = _stream.EndRead(ar);

            if (bytesRead == 0)
            {
                _client.Close();
                return;
            }

            // 解析JSON
            string json = Encoding.UTF8.GetString(buffer, 0, bytesRead);
            dynamic data = JsonConvert.DeserializeObject(json);

            Console.WriteLine();
            // 处理业务逻辑（示例：打印接收到的数据）
            Console.WriteLine("接收客户端信息：");
            Console.WriteLine(json);

            if (json.Contains("GET_PRINT_LOT_INFO"))
            {
                //string response = JsonConvert.SerializeObject(new { Status = "服务器已经收到", Message = "Data received" });
                //string response = JsonConvert.SerializeObject(new { ServerResponse = "OK,DQCZ3017H1DT00\r\n"});
                
                string response = "OK,DQCZ3017H1DT00\r\n";
                byte[] responseBytes = Encoding.UTF8.GetBytes(response);
                _stream.Write(responseBytes, 0, responseBytes.Length);

                Console.WriteLine();
                // 处理业务逻辑（示例：打印接收到的数据）
                Console.WriteLine("返回给客户端信息：");
                Console.WriteLine(response);
            }
            else
            {
                //string response = JsonConvert.SerializeObject(new { Status = "服务器已经收到", Message = "Data received" });
                //string response = JsonConvert.SerializeObject(new { ServerResponse = "“NG,Invalid Client Machine\r\n" });

                string response = "NG,Invalid Client Machine\r\n";
                byte[] responseBytes = Encoding.UTF8.GetBytes(response);
                _stream.Write(responseBytes, 0, responseBytes.Length);

                Console.WriteLine();
                // 处理业务逻辑（示例：打印接收到的数据）
                Console.WriteLine("返回给客户端信息：");
                Console.WriteLine(response);
            }

            // 返回ACK响应
            

            // 继续监听新数据
            StartReceiving();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error processing data: {ex.Message}");
            _client.Close();
        }
    }
}